package homework.shiwu2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class TransactionHandler implements InvocationHandler {
    private final Object target; // 目标对象

    public TransactionHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            // 开启事务
            System.out.println("开启事务");

            // 调用目标方法
            Object result = method.invoke(target, args);

            // 提交事务
            System.out.println("提交事务");

            return result;
        } catch (Exception e) {
            // 回滚事务
            System.out.println("回滚事务");
            throw e;
        }
    }
}
